package cn.sh.cares.tools.srcgen;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.sh.cares.tools.srcgen.db.DatabaseIntrospector;
import cn.sh.cares.tools.srcgen.db.TableDefinition;
import cn.sh.cares.tools.srcgen.freemarker.DAOGenerator;
import cn.sh.cares.tools.srcgen.freemarker.DAOImplGenerator;
import cn.sh.cares.tools.srcgen.freemarker.IBatisSQLMapGenerator;
import cn.sh.cares.tools.srcgen.freemarker.POJOGenerator;
import cn.sh.cares.tools.srcgen.generate.DefaultNameConverter;
import cn.sh.cares.tools.srcgen.util.ResourceManager;

public class SourceGenerator {

	static final String DRIVER_CLASS = ResourceManager.getMessage("jdbc.driverClass");
	static final String URL = ResourceManager.getMessage("jdbc.url");
	static final String USER_NAME = ResourceManager.getMessage("jdbc.username");
	static final String PASSWORD = ResourceManager.getMessage("jdbc.password");
	static final String CATALOG = ResourceManager.getMessage("jdbc.catalog");
	static final String SCHEMA = ResourceManager.getMessage("jdbc.schema");

	private static final Log log = LogFactory.getLog(SourceGenerator.class);  
	
	private List<Generator> generators = new ArrayList<Generator>();
	
	public SourceGenerator(){}
	
	public SourceGenerator(Generator g) {
		generators.add(g);
	}
	
	public SourceGenerator(List<Generator> gs) {
		generators.addAll(gs);
	}

	public void add(Generator g) {
		generators.add(g);
	}
	
	public void generate() {
		log.debug("generate start...");
		try {
			Class.forName(DRIVER_CLASS);
			Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
			
			DatabaseIntrospector p = new DatabaseIntrospector(connection.getMetaData(), new DefaultNameConverter());
			
			List<TableDefinition> tableDefinitions = p.introspectTables(CATALOG, SCHEMA);
			
			for (Generator g : generators) {
				g.generate(tableDefinitions);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			log.debug("generate end...");
		}
	}
	
	public static void main(String[] args) {
		SourceGenerator sg = new SourceGenerator(new POJOGenerator());
		sg.add(new IBatisSQLMapGenerator());
		sg.add(new DAOGenerator());
		sg.add(new DAOImplGenerator());
		sg.generate();
	}
}
